package com.gxstnu.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxstnu.entity.User;
import com.gxstnu.exception.CustomerException;
import com.gxstnu.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;

    public void add(User user) {
        // 根据新的账号查询数据库  是否存在同样账号的数据
        User dbUser = userMapper.selectByName(user.getName());
        if (dbUser != null) {
            throw new CustomerException("账号重复");
        }
        // 默认密码
        if (StrUtil.isBlank(user.getPassword())) {
            user.setPassword("user");
        }
        userMapper.insert(user);
    }

    public List<User> selectAll(User user){
        return userMapper.selectAll(user);
    }

    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize,User user ) {
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    public void update(User user) {
        userMapper.updateById(user);

    }

    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    public void deleteBatch(List<User> list) {
        for (User user : list) {
            deleteById(user.getId());
        }
    }

    public User login(User user) {
        //验证账号是否存在
        User dbUser = userMapper.selectByName(user.getName());
        if(dbUser == null)
            throw new CustomerException("账号不存在");
        //验证密码是否正确
        if(!dbUser.getPassword().equals(user.getPassword()))
            throw new CustomerException("密码错误");
            
        // 生成token (使用用户名和时间戳组合)
        String token = user.getName() + "_" + System.currentTimeMillis();
        dbUser.setToken(token);
        
        return dbUser;
    }

    public void register(User user) {
        this.add(user);
    }
}
